/*
 * @(#)JsIncludeTag.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.staff.taglib;

import java.sql.Connection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.util.ResponseUtils;

import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.staff.bean.StaffHierarchy;
import com.dcivision.staff.dao.StaffHierarchyDAObject;

/**
 * <p>Class Name:    StaffTreeTag.java    </p>
 * <p>Description: This tag is to display the staff hierarchy tree. The stafftree 
 * can be * passed in using the <code>parentID</code> attribute, and the <code>action</code> attribute.<p>
 *
 * Below is a sample usage to display the staff hierarchy tree. <p>
 * &lt;staff:staffTree parentID="0" action="ListStaffRecord.do" &gt;<br>
 * 
 * @author waison hu
 * @company DCIVision Limited
 * @creation date 19/06/2007
 * @version $Revision: 1.1.2.4 $
 */

public class StaffTreeTag extends TagSupport {

  public static final String REVISION = "$Revision: 1.1.2.4 $";

  final int MAX_LVL = Integer.parseInt(SystemParameterFactory.getSystemParameter(SystemParameterConstant.STAFF_HIERARCHY_LEVEL));

  protected Log log = LogFactory.getLog(this.getClass().getName());

  protected String parentID = "0";
  protected String action = null;

  protected List fullStaffList = null;
  
  private StringBuffer sbJstCode = null;

  /**
   * Render the specified message messages if there are any.
   * 
   * @exception JspException if a JSP exception has occurred
   */
  public int doStartTag() throws JspException {
    fullStaffList = getStaffListFromDao();
    createWebFXTree();
    // Continue processing this page
    return (EVAL_BODY_INCLUDE);
  }

  private boolean createWebFXTree() throws JspException {
    sbJstCode = new StringBuffer();
    String preference = SystemParameterFactory.getSystemParameter(SystemParameterConstant.PREFERENCE);
    String contextPath = (String) this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);
    SessionContainer sessionContainer = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    if ((sessionContainer!=null) && (sessionContainer.getUserRecord()!=null)) {
      if (sessionContainer.getUserRecord().getPreference()!=null) {
        preference = sessionContainer.getUserRecord().getPreference().toString();
      }
    }
    String imgPath = contextPath + "/theme/pref" + preference + "/img/common/";

    sbJstCode.append("<script type=\"text/javascript\"> \n");
    sbJstCode.append("<!-- \n");
    sbJstCode.append("if (document.getElementById) { \n");

    sbJstCode.append("webFXTreeConfig.folderIcon = \"" + imgPath + "IconTreeStaff.gif" + "\"; \n");
    sbJstCode.append("webFXTreeConfig.openFolderIcon = \"" + imgPath + "IconTreeStaff.gif" + "\"; \n");
    sbJstCode.append("webFXTreeHandler.currentID = \"" + parentID + "\"; \n");
    sbJstCode.append("var currentName=\"\"; \n");
    
    if(action!=null)
    sbJstCode.append("var node0 = new WebFXTree('"
        + TextUtility.replaceString(SystemParameterFactory.getSystemParameter(SystemParameterConstant.COMPANY_NAME), "'", "\\'")
        + " ','" + action + "?parentID=0&levelNo=1', '0'); \n");
    else
      log.error("action is null.");
    sbJstCode.append("node0.setBehavior('explorer'); \n");    

    // int grandParentID = 0;
    List list = fullStaffList;

    for (int i = 1; i <= list.size(); ++i) {
      StaffHierarchy staff = (StaffHierarchy) list.get(i - 1);
      int level = staff.getLevelNo().intValue();     
      
      if(staff.getID().intValue()==Integer.valueOf(parentID).intValue()){
        sbJstCode.append("currentName=\""+ 
                 TextUtility.replaceString(staff.getName(), "'", "\\'") +"\"; \n");
      }
      
      if (level < MAX_LVL) {
        if(action!=null)
        sbJstCode.append(" var node" + staff.getID() + "= new WebFXTreeItem('" + TextUtility.replaceString(staff.getName(), "'", "\\'")
            + "','" + action +"?parentID=" + staff.getID() +"&labelFieldValue="+staff.getID()+ 
            "&levelIndex="+level+"&levelNo=" + (level + 1) + "&parentName=" +  TextUtility.replaceString(staff.getName(), "'", "\\'") +
            "', " + "'" + staff.getID()
            + "'); \n");
        else{
          log.error("action is null.");
        }
      } else {
        log.debug("level >= MAX_LVL , these nodes will not create .");
      }
    }
    // add all nodes to their parent nodes
    for (int i = 1; i <= list.size(); ++i) {
      sbJstCode.append("if ( typeof node" + ((StaffHierarchy) list.get(i - 1)).getParentID() + "!= \"undefined\" &&" +
                    "typeof node" + ((StaffHierarchy) list.get(i - 1)).getID() + "!= \"undefined\" ) { \n");
      sbJstCode.append("  node" + ((StaffHierarchy) list.get(i - 1)).getParentID() + ".add( node"
          + ((StaffHierarchy) list.get(i - 1)).getID() + "); \n");
      sbJstCode.append("}");
    }
    
    sbJstCode.append("document.write('<div class=\"dtree\">'); \n");
    sbJstCode.append("document.write(node0); \n");
    sbJstCode.append("document.writeln('</div>'); \n");
    
    sbJstCode.append("} \n");
    
    sbJstCode.append("//--> \n");
    sbJstCode.append("</script> \n");

    // Print the results to our output writer
    ResponseUtils.write(pageContext, sbJstCode.toString());
    return true;
  }
  
  public int doEndTag() throws JspException {
    this.release();
    return EVAL_PAGE;
  }

  /**
   * release
   * 
   * Release any acquired resources.
   */
  public void release() {
    sbJstCode = null;
    super.release();
  }

  private List getStaffListFromDao() {
    List staffList = null;
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    SessionContainer sessionCon = (SessionContainer) request.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = null;

    try {
      conn = DataSourceFactory.getConnection();
      StaffHierarchyDAObject dao = new StaffHierarchyDAObject(sessionCon, conn);
      staffList = dao.getFullList();
    } catch (Exception exp) {
      log.error("can't getConnection to DB!");
    } finally {
      try {
        if (conn != null)
          conn.close();
      } catch (Exception ex) {
        log.error("close DB connection error!");
      } finally {
        conn = null;
      }
    }

    return staffList;
  }

  public String getParentID() {
    return parentID;
  }

  public void setParentID(String parentID) {
    this.parentID = parentID;
  }

  public String getAction() {
    return action;
  }

  public void setAction(String action) {
    this.action = action;
  }

}
